package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbProdAttaMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbProdAtta;
import com.bwie.pojo.TbProdInfo;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ProdInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_prod(商品表)】的数据库操作Service实现
* @createDate 2025-07-21 15:23:46
*/
@Service
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
    implements TbProdService{
    @Autowired
    TbProdMapper prodMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    FastFileStorageClient fastFileStorageClient;
    @Autowired
    TbProdAttaMapper prodAttaMapper;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    /**
     * @author LiuWeiChen
     * @description 获取商品列表
     * @params [pageInfoVo]
     * @return com.bwie.utils.R
     * @date 2025/7/23 10:34
    */
    @Override
    public R getPageListProd(PageInfoVo pageInfoVo) {
        Page<TbProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TbProd> tbProdPage = prodMapper.getPageListProd(page, pageInfoVo);
        return R.OK(tbProdPage);
    }

    @Override
    public R addProd(TbProd tbProd) {
        //SPU和商品名称重复校验
        TbProd prod = prodMapper.selectOne(
                new QueryWrapper<TbProd>().lambda()
                        .eq(TbProd::getProdSpu, tbProd.getProdSpu())
                        .or()
                        .eq(TbProd::getProdName, tbProd.getProdName())
        );
        if (prod != null) {
            return R.ERROR(500, "商品已存在");
        }

//        String token = request.getHeader("token");
//        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
//        String userName = body.get("userName", String.class);
//        tbProd.setCreateBy(userName);
//        tbProd.setCreateTime(new Date());



        prodMapper.insert(tbProd);
        return R.OK();
    }

    @Override
    public R uploadFile(MultipartFile file) {
        String extName = FileNameUtil.extName(file.getOriginalFilename());
        StorePath storePath = null;
        try {
            storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://192.168.80.192:8888/" + storePath.getFullPath();
            return R.OK(url);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return R.ERROR(500, "上传失败");
        }
    }

    @Override
    public R deleteBatchProd(List<Integer> ids) {
        //批量删除商品
        prodMapper.deleteBatchIds(ids);
        //批量删除商品附件
        prodAttaMapper.delete(
                new QueryWrapper<TbProdAtta>().lambda().in(TbProdAtta::getProdId, ids)
        );
        return R.OK();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteProd(Integer prodId) {
        //判断商品是存在
        TbProd tbProd = prodMapper.selectById(prodId);
        if (tbProd == null) {
            return R.ERROR(500, "商品不存在");
        }
        //删除商品
        prodMapper.deleteById(prodId);
        return R.OK();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addProdAtta(TbProdAtta tbProdAtta) {
        //判断商品是否存在
        TbProd tbProd = prodMapper.selectById(tbProdAtta.getProdId());
        if (tbProd == null) {
            return R.ERROR(500, "商品不存在");
        }
        //删除原有附件  根据商品的ID进行删除
        int delete = prodAttaMapper.delete(
                new QueryWrapper<TbProdAtta>().lambda().eq(TbProdAtta::getProdId, tbProdAtta.getProdId())
        );
        tbProdAtta.setCreateTime(new Date());
        //添加附件
        prodAttaMapper.insert(tbProdAtta);
        return R.OK();
    }

    @Override
    public R getProdById(Integer prodId) {

        //--1
        TbProd tbProd = getById(prodId);
        if(tbProd == null) {
            return R.ERROR(500, "商品不存在");
        }

        //--2

        return R.OK(tbProd);
    }

    @Override
    public R getProdInfoList(ProdInfoVo prodInfoVo) {

        //--1
        Page<TbProdInfo> page = new Page<>(prodInfoVo.getPageNum(), prodInfoVo.getPageSize());

        //--2
        QueryWrapper<TbProdInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(TbProdInfo::getProdId, prodInfoVo.getProdId())
                .orderByAsc(TbProdInfo::getInfoId);
        Page<TbProdInfo> tbProdInfoPage = tbProdInfoMapper.selectPage(page, wrapper);

        return R.OK(tbProdInfoPage);
    }

    @Override
    public R addProdInfo(TbProdInfo tbProdInfo) {

        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        String userName = TokenUtil.getUserName(token);

        //--1 判断商品是否存在
        TbProd tbProd = getById(tbProdInfo.getProdId());
        if(tbProd == null) {
            return R.ERROR(500, "商品不存在");
        }

        //--2 判断商品SKU是否存在
        QueryWrapper<TbProdInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbProdInfo::getProdId, tbProdInfo.getProdId())
                .eq(TbProdInfo::getProdName, tbProdInfo.getProdName());
        TbProdInfo one = tbProdInfoMapper.selectOne(wrapper);
        if(one != null) {
            return R.ERROR(500, "商品SKU已存在");
        }

        //--3 添加商品信息
        tbProdInfo.setCreateTime(new Date());
        tbProdInfo.setCreateBy(userName);
        tbProdInfoMapper.insert(tbProdInfo);

        return R.OK();
    }

    @Override
    public R selectProdInfo() {
        List<TbProdInfo> list = tbProdInfoMapper.selectList(null);
        return R.OK(list);
    }

}




